<template>
  <button @click="handleClick" :class="{ [disabledClass]: counting }">
    {{ text }}
  </button>
</template>
<script>
export default {
  name: "CountDown",
  props: {
    times: {
      type: Number,
      default: 60
    },
    countingText: {
      type: String,
      default: "重新获取(##)s"
    },
    defaultText: {
      type: String,
      default: "获取验证码"
    },
    disabledClass: {
      type: String,
      default: "disabled"
    }
  },
  data() {
    return {
      text: "",
      count: 0,
      counting: false,
      time: 0
    };
  },
  mounted() {
    this.reset();
  },
  methods: {
    start() {
      this.counting = true;

      this.time = setInterval(() => {
        this.count -= 1;

        this.text = this.countingText.replace("##", this.count);

        if (this.count <= 0) {
          this.reset();
        }
      }, 1000);
    },
    reset() {
      clearInterval(this.time);
      this.counting = false;
      this.text = this.defaultText;
      this.count = this.times;
    },
    handleClick() {
      if (this.counting) {
        this.$emit("counting");
      } else {
        this.$emit("click");
      }
    }
  }
};
</script>
